package com.onekbase.demo.tcp;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.*;

public class TcpServerNioThreadPoolDemo {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        int port = 8084;
        serverSocketChannel.bind(new InetSocketAddress("localhost", port));
        serverSocketChannel.configureBlocking(false);
        System.out.println("Server started on port "+port);
        ExecutorService executorService = new ThreadPoolExecutor(100,100 ,
                5000L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
        while (true) {
            SocketChannel socketChannel = serverSocketChannel.accept();
            if (socketChannel != null) {
                executorService.submit(() -> {
                    try {
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        int bytesRead = socketChannel.read(buffer);
                        if (bytesRead > 0) {
                            buffer.flip();
                            byte[] data = new byte[buffer.remaining()];
                            buffer.get(data);
                            String receivedData = new String(data);
                            System.out.println("Received: " + receivedData);
                        }
                        Thread.sleep(200);
                        String response = "response data from server client";
                        ByteBuffer responseBuffer = ByteBuffer.wrap(response.getBytes());
                        socketChannel.write(responseBuffer);
                        socketChannel.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        }
    }
}
